import {createRouter, createWebHistory, RouteRecordRaw} from 'vue-router';
import login from "../Navigation/conponment/Login.vue";
import request from "../utils/request";
import Default from "../Navigation/default.vue";
import admin from "./routes/admin.vue";

// 路由配置
const routes = [
    {
        path: '/login',
        name:'login',
        component: login,
    },
    {
        path: '/default',
        name:'default',
        component: Default,
    },
    {
        path: '/admin',
        name:'admin',
        component: admin,
    }

];
const dynamicRoutes: RouteRecordRaw[] = [];
// 创建路由实例
const router = createRouter({
    history: createWebHistory(), // 使用 HTML5 History 模式
    routes,
});
async function loadDynamicRoutes() {
    try {
        const response = await request.get('/api/user/book/list');
        console.log('Books Response:', response);

        if (!Array.isArray(response.data.data)) {
            throw new Error('接口返回的数据不是数组');
        }

        response.data.data.forEach((book: any) => {
            const bookRoute: RouteRecordRaw = {
                path: `/book/:bookId`, // 使用动态参数 :bookId
                name: `Book-${book.id}`,
                component: () => import('../views/BookDetail.vue'),
                props: true, // 将动态参数作为组件的 props 传递
                children: Array.isArray(book.sectionList)
                    ? book.sectionList.map((section: any) => ({
                        path: `section/:sectionId`, // 使用动态参数 :sectionId
                        name: `Section-${section.id}`,
                        component: () => import('../views/SectionDetail.vue'),
                        props: true, // 将 sectionId 作为 props 传递到组件
                    }))
                    : [], // 如果 sectionList 为空或无效，则使用空数组
            };

            dynamicRoutes.push(bookRoute);
        });

        // 动态添加路由到路由实例
        dynamicRoutes.forEach((route) => router.addRoute(route));
    } catch (error) {
        console.error('加载动态路由失败:', error);
    }


}

loadDynamicRoutes();

export default router;
